<!--
 * @Author: Dorange.Wang
 * @Date: 2021-04-20 09:12:40
 * @LastEditors: your name
 * @LastEditTime: 2021-04-20 12:39:33
 * @Description: file content
-->
<template>
  <el-dialog
    :visible="showVisible"
    center
    :show-close="false"
    width="900px"
    class="code-editor-dialog"
  >
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ '编写脚本' }}</span>
        <span
          class="el-icon-close g9 f26 poi"
          @click="showVisible = false"
        ></span>
      </div>
    </div>

    <div class="content">
      <el-select
        class="lang-selector"
        v-model="lang"
      >
        <el-option v-for="(value,key) in SCRIPT_TYPE_ENUM" :key="key" :value="key" :label="value"/>
      </el-select>
      <codemirror
        v-model="code"
        :options="options"
      />
    </div>

    <div slot="footer" class="tr">
      <el-button @click="showVisible = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>

  </el-dialog>
</template>

<script>
import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/cobalt.css'
import 'codemirror/mode/javascript/javascript.js'
import { SCRIPT_TYPE_ENUM } from '@/utils/enum'

const defaultLang = Object.keys(SCRIPT_TYPE_ENUM)[0]

export default {
  name: 'CodeEditor',
  components: {
    codemirror
  },
  data () {
    return {
      SCRIPT_TYPE_ENUM,
      showVisible: false,
      code: '',
      lang: '',
      options: {
        tabSize: 2,
        styleActiveLine: true,
        lineNumbers: true,
        line: true,
        foldGutter: true,
        styleSelectedText: true,
        mode: 'text/javascript',
        // keyMap: 'sublime',
        matchBrackets: true,
        showCursorWhenSelecting: true,
        theme: 'cobalt',
        extraKeys: { 'Ctrl': 'autocomplete' },
        hintOptions: {
          completeSingle: false
        }
      },
      callback: null
    }
  },

  methods: {
    open (option = {}, callback) {
      const { code, lang } = option
      this.code = code
      this.lang = lang || defaultLang
      this.callback = callback
      this.showVisible = true
    },

    submit () {
      const { code, lang } = this
      this.showVisible = false
      this.callback && this.callback({
        code, lang
      })
      this.code = ''
      this.lang = ''
    }
  }
}
</script>

<style lang="scss">
.code-editor-dialog{
  .el-dialog__body{
    padding: 0 !important;
  }

  .CodeMirror{
    height: 50vh;
  }

  .content{
    position: relative;
  }

  .lang-selector{
    position: absolute;
    top: 5px;
    right: 5px;
    z-index: 1000;
    width: 120px;
  }
}
</style>
